#!/usr/bin/env python
# # -*- coding: utf-8 -*-

"""
@File:      global_functions.py
@Author:    Jim.Dai.Cn
@Date:      2024/6/11 20:14
@Desc:         
"""

from datetime import datetime, timedelta
import docx
import pytz
from dateparser import parse

def str_get_current_date_time() -> str:
    """
    返回 当前时间的 YYYYMMDDHHMMSS 字符串。通常用于精确到秒的文件名生成
    :return: str 当前时间的 YYYYMMDDHHMMSS 字符串
    """
    now = datetime.now()
    return now.strftime('%Y%m%d_%H%M%S')


def date_to_ts(str_date, str_zone='Asia/Shanghai') -> float:
        tz_info = pytz.timezone(str_zone)  # 北京时间
        # todo : 时区设置修正
        dt_obj = datetime.strptime(str_date, "%Y-%m-%d %H:%M:%S")
        dt_obj = tz_info.localize(dt_obj)
        ts = dt_obj.timestamp()
        return ts


def is_weekday(date):
    """判断给定的日期是不是工作日（非周六和周日）。"""
    return date.weekday() < 5  # weekday() 返回的是一个0-6的整数，0是周一，6是周日


def days_between(str_start, str_end, str_format='%Y-%m-%d %H:%M:%S'):
    """计算两个日期之间的天数"""
    # start_date = datetime.strptime(str_start, str_format)
    # end_date = datetime.strptime(str_end, str_format)
    start_date = parse(str_start)
    end_date = parse(str_end)
    if (start_date is None) or (end_date is None):
        return 0
    delta = end_date - start_date
    return delta.days


def business_days_between(str_start, str_end, str_format='%Y-%m-%d %H:%M:%S'):
    """计算两个日期之间的工作日天数，不考虑公共假期。"""
    start_date = datetime.strptime(str_start, str_format)
    end_date = datetime.strptime(str_end, str_format)
    if start_date >= end_date:
        return 0
    current_date = start_date
    business_days = 0

    while current_date <= end_date:
        if is_weekday(current_date):
            business_days += 1
        current_date += timedelta(days=1)

    return business_days


def read_from_doc(path) -> list:
    file = docx.Document(path)
    res = []
    for p in file.paragraphs:
        res.append(p.text)
    return res


def read_from_doc_to_string(path) -> str:
    file = docx.Document(path)
    content = ''
    res = []
    for p in file.paragraphs:
        content = content + "\n" + p.text
    content = content.replace('\xa0', ' ')
    return content


def doc_to_history(arr_doc, str_prefix='请阅读以下文本') -> list:
    # history = []
    history = str_prefix
    for r in arr_doc:
        # history.append({'text': r})
        history = history + r
    history = history.replace('\xa0', ' ')
    messages = [{
        'role': 'user',
        'content': history
    }]
    return messages


def doc_to_history_arr(arr_doc) -> list:
    history = []
    for r in arr_doc:
        history.append({'text': r})
    messages = [{
        'role': 'user',
        'content': history
    }]
    return messages


def doc_to_string(arr_doc) -> str:
    history = ''
    for r in arr_doc:
        history = history + "\n" + r

    return history

